package com.corecloud.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.corecloud.config.SSLClient;
import com.corecloud.entity.SysUserEntity;
import com.corecloud.service.SysUserService;
import com.corecloud.tools.AjaxResultData;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

/***
 * 手机短信验证码发送
 * @author
 */
@Component
public class VerifyController {

	private static HttpClient httpclient;

	@Autowired
	RedisTemplate redisTemplate;

	@Autowired
	SysUserService sysUserService;

	private static SysUserService sysUserServices;
	private static RedisTemplate redisTemplates;

	@PostConstruct
	public void init(){
		//注入的对象由静态对象管理
		sysUserServices = this.sysUserService;
		redisTemplates = this.redisTemplate;
	}

	/**
	 * 短信发送请求
	 * @param mobile：手机号
	 * @param verifyCode：验证码
	 * @return
	 * 200：代表正常
	 * 121：代表无该收手机号信息
	 * 122：代表该用户实名认证未完善
	 * @throws Exception
	 */
	public Integer sendSms(String mobile, String verifyCode, String codePhoneType) throws Exception {
		QueryWrapper<SysUserEntity> phone1 = new QueryWrapper<SysUserEntity>();
		SysUserEntity phone = new SysUserEntity();

		if(!StringUtils.isEmpty(mobile)) {
			phone1.eq("phone", mobile);
			phone = sysUserServices.selectOne(phone1);
		}

		if (codePhoneType.equals("1")){
			if (phone == null){
				smslog(verifyCode, mobile);
				return 200;
			}else {
				return 123;//手机号被注册
			}
		}else {
			if (phone != null){
				if (phone.getIdCard() != null && phone.getName() != null){
					smslog(verifyCode, mobile);
				}else {
					return 122;//该用户实名认证未完善
				}
			}else {
				return 121;//无该收手机号信息
			}
			return 200;//正常
		}
	}

	public void smslog(String verifyCode, String mobile) throws Exception{
//		返回的信息
		String message = "";

		httpclient = new SSLClient();
		String text = "【中博科技】您的验证码为：" + verifyCode + "，有效时间为15分钟，如非本人操作，请忽略此信息。";

//		        短信接口请求地址
		String url = "https://dx.ipyy.net/sms.aspx";
		HttpPost post = new HttpPost(url);
		post.setHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");

		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//		        发送任务命令(设置为固定的:send)
		nvps.add(new BasicNameValuePair("action","send"));
//		        企业ID(不验证，可不填)
		nvps.add(new BasicNameValuePair("userid", ""));
//		        实际账号名
		nvps.add(new BasicNameValuePair("account", "ZZ00290"));
//		        实际发送密码
		nvps.add(new BasicNameValuePair("password", "1A202E886133FA6C7780B1F2BD739FD5"));
//		        多个手机号用逗号分隔
		nvps.add(new BasicNameValuePair("mobile", mobile));
//		        发送内容(短信的内容，内容需要UTF-8编码，提交内容格式：内容+【签名】。签名是公司的名字或者公司项目名称。
//		        示例：您的验证码：1439【中博】。【】是签名的标识符。请按照正规的格式提交内容测试，请用正规内容下发，
//		        最好不要当成是测试，就当是正式使用在给自己的客户发信息，签名字数3-8个字)
		nvps.add(new BasicNameValuePair("content", text));
//		        定时发送时间(为空表示立即发送，定时发送格式2010-10-24 09:08:10（可选）)
		nvps.add(new BasicNameValuePair("sendTime", ""));
//		        扩展子号(请先询问配置的通道是否支持扩展子号，如果不支持，请填空。子号只能为数字，且最多5位数。（可选）)
		nvps.add(new BasicNameValuePair("extno", ""));

		post.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));

		HttpResponse response2 = httpclient.execute(post);

		try {
			System.out.println(response2.getStatusLine());
			HttpEntity entity = response2.getEntity();
			/*将字符转化为XML*/
			String returnString = EntityUtils.toString(entity, "UTF-8");
			Document doc = DocumentHelper.parseText(returnString);
			/*System.out.println(returnString);*/
			/*获取根节点*/
			Element rootElt = doc.getRootElement();

			/*获取根节点下的子节点的值 返回状态值：成功返回Success 失败返回：Fail*/
			/*System.out.println("返回状态为：" + rootElt.elementText("returnstatus").trim());
//			返回信息提示
			System.out.println("返回信息提示：" + rootElt.elementText("message").trim());
//			返回短信剩余余额次数
			System.out.println("返回余额：" + rootElt.elementText("remainpoint").trim());
//			返回任务批次(返回本次任务的序列ID)
			System.out.println("返回任务批次：" + rootElt.elementText("taskID").trim());
//			返回的成功条数(成功短信数：当成功后返回提交成功短信数)
			System.out.println("返回成功条数：" + rootElt.elementText("successCounts").trim());*/

			/*释放资源*/
			EntityUtils.consume(entity);
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
	}
}
